#include "mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QDateTime>
#include <QTime>
#include "./Lib/hidapi/include/hidapi.h"

#define vid 0x0483
#define pid 0x1033

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent) {
    this->initLayout();      // 初始化布局
    this->initListener();    // 初始化监听
}

MainWindow::~MainWindow() {
    hid_close(handle);
    if (handle != nullptr) {
        handle = nullptr;
    }
    this->spmContainner = nullptr;
    this->spmContainnerLeft = nullptr;
    this->spmContainnerCenter = nullptr;
    this->tlVid = nullptr;
    this->tlPid = nullptr;
    this->btOpen = nullptr;
    this->lbStatus = nullptr;
    this->teView = nullptr;
    this->teSend = nullptr;
    this->btnSend = nullptr;
}

void MainWindow::initLayout() {
    // 主容器 spm_containner
    this->spmContainner = new QSplitter(Qt::Horizontal, 0);

    // 主容器的左边
    this->spmContainnerLeft = new QSplitter(Qt::Vertical, spmContainner);
    QSplitter* buttonSplitter = new QSplitter(Qt::Horizontal, spmContainnerLeft);
    this->lbStatus = new QLabel("未连接");
    this->lbStatus->setAlignment(Qt::AlignCenter);
    buttonSplitter->addWidget(lbStatus);
    this->btOpen = new QPushButton("打开");
    buttonSplitter->addWidget(btOpen);
    spmContainnerLeft->addWidget(buttonSplitter);
    QTextEdit* leftOfBottom = new QTextEdit("刷新列表 占位符");
    leftOfBottom->setAlignment(Qt::AlignCenter);
    spmContainnerLeft->addWidget(leftOfBottom);
    spmContainnerLeft->setStretchFactor(0, 1);
    spmContainnerLeft->setStretchFactor(1, 4);

    // 主容器的中间
    this->spmContainnerCenter = new QSplitter(Qt::Vertical, spmContainner);
    // 预览框
    this->teView = new QTextEdit();
    this->spmContainnerCenter->addWidget(teView);
    // 输入框
    this->teSend = new QTextEdit();
    this->spmContainnerCenter->addWidget(teSend);
    // 发送按钮
    this->btnSend = new QPushButton("发送");
    this->spmContainnerCenter->addWidget(btnSend);
    this->spmContainnerCenter->setStretchFactor(0, 3);
    this->spmContainnerCenter->setStretchFactor(1, 1);
    this->spmContainnerCenter->setStretchFactor(2, 1);

    // 布局大小设定
    spmContainner->setStretchFactor(0, 1);  // 左边 占比1
    spmContainner->setStretchFactor(1, 3);  // 中间 占比2
    spmContainner->setWindowTitle("Hid");
    spmContainner->setFixedSize(600, 300);
    spmContainner->show();
}

void MainWindow::initListener() {
    /** 定时器 */
    timer = new QTimer(this);
    timer->setInterval(100);        // 100ms
    timer->setSingleShot(false);    // 周期性触发
    connect(timer, SIGNAL(timeout()), this, SLOT(updateRecieve()));

    /** 打开连接 */
    connect(this->btOpen, &QPushButton::clicked, this, [=]() {
        int res;
        res = hid_init();
        this->handle = hid_open(vid, pid, NULL);
        if (!handle) {
            QMessageBox::information(nullptr, "提示", "无法打开设备!");
            hid_exit();
        }
        else {
            QMessageBox::information(nullptr, "提示", "设备打开成功!");
        }
        timer->start();
        });

    /** 发送按钮 */
    connect(this->btnSend, &QPushButton::clicked, this, [=]() {
        unsigned char sendBuf[65] = { 0 };
        QString str = this->teSend->toPlainText();
        // 将QString转换为uchar*
        for (int i = 1;i < str.length() + 1;i++) {
            sendBuf[i] = str.at(i - 1).cell();
        }
        hid_write(this->handle, sendBuf, str.length() + 1);
        });
}

/**
 * 100ms 执行一次
*/
void MainWindow::updateRecieve() {
    /** 读取新的数据 */
    if (this->handle != NULL) {
        unsigned char buf[65];
        hid_set_nonblocking(this->handle,1);
        int rep = hid_read(this->handle, buf, 65);
        if (rep > 0) {
            char perCh[4]={0};
            QString str;
            str.append(QTime::currentTime().toString("时间: hh:mm:ss:zzz  >>>\n"));
            for(int i =0;i<rep;i++){
                sprintf(perCh,"%02d ",buf[i]);
                str.append(perCh);
                if((i+1)%4==0){
                    str.append("  ");
                }
                if((i+1)%8==0){
                    str.append("\n");
                }
            }
            str.append("\n");
            this->teView->append(str);
        }
    }

    /** 检查设备是否连接 */
    if (hid_get_device_info(this->handle) != NULL) {
        this->lbStatus->setText("已连接");
    }else {
        // 做重连
        this->lbStatus->setText("断开连接");
//        this->handle = hid_open(vid, pid, NULL);
    }
}
